<template>
  <view>
    <view class="page-header">
      <view class="back-icon" @click="goBack">
      </view>
    </view>
    <view class="address-list">
      <view class="address-item" v-for="(item, index) in addressList" :key="index">
        <view class="contact-info">
          <view class="name">{{ item.name }}</view>
          <view class="phone">{{ item.phone }}</view>
        </view>
        <view class="address">{{ item.city }}{{ item.department}}{{ item.houseNumber}}</view>
        <view class="edit-icon" @click="editAddress(index)">
          <image src="../../static/imgs/编辑.png" mode="aspectFit" style="width: 20px; height: 20px;" />
        </view>
      </view>
    </view>
    <button class="create-address-btn" @click="createAddress">新建收货地址</button>
  </view>
</template>
<script>
import config from '../config.js';
export default {
  data() {
    return {
      addressList: []
    };
  },
  onShow() {
    this.Adress();
  },
  onLoad(options) {
    if (options.addressList) {
        this.adresslist = JSON.parse(options.addressList);
    } else {
        this.loadDefaultAddress();
    }
},
  methods: {
    Adress() {
      uni.request({
        url: config.api_host+`/address`,
        success: (res) => {
          this.addressList = res.data;
        },
        fail: (err) => {
          console.error('获取地址列表失败:', err);
        }
      });
    },
     selectAddress(address) {
        // 选择地址后返回上一页并传递选中的地址
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        prevPage.setData({
            defaultAddress: address
        });
        uni.navigateBack();
    },
    goBack() {
      uni.navigateBack();
    },
   editAddress(index) {
    const addressId = this.addressList[index].id;
    console.log('编辑地址，ID:', addressId);
    uni.navigateTo({
      url: `/pages/dingdan/edit-adress?id=${addressId}`
    });
  },
    createAddress() {
        uni.navigateTo({
        url:`/pages/dingdan/new-adress`
      })
      // 这里可以跳转到新建地址页面
    }
  }
};
</script>

<style>
.page-header {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 25px;
  background-color: #f8f8f8;
}
.back-icon {
  position: absolute;
  left: 20px;
  font-size: 24px;
  color: #333;
}
.address-list {
  padding: 10px;
}
.address-item {
  background-color: #fff;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.contact-info {
  display: flex;
}
.name {
  font-size: 16px;
  color: #666;
  margin-right: 20px;
}
.phone {
  font-size: 16px;
  color: #666;
}
.address {
  font-size: 16px;
  color: #333;
}
.edit-icon {
  cursor: pointer;
}
.create-address-btn {
  display: block;
  width: 100%;
  height: 45px;
  background-color:#0091ff;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  margin-top: 10px;
}
</style>

